using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Barbar.MapReport.HtmlRender.Handlers {
  internal class HandlerUrl {
    private StringBuilder m_Suffix = new StringBuilder();
    private bool m_IsFirst = true;

    public HandlerUrl() {
    }

    public HandlerUrl(Type handlerType) {
      AddParameter("type", handlerType.ToString());
    }

    public static string Url {
      get {
        string url = HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped) + HttpRuntime.AppDomainAppVirtualPath;
        if (!url.EndsWith("/", StringComparison.Ordinal))
          url = url + "/";
        return url + "MapResource.ashx";
      }
    }

    public void AddParameter(string key, string value) {
      if (m_IsFirst) {
        m_Suffix.Append("?");
        m_IsFirst = false;
      } else
        m_Suffix.Append("&");
      m_Suffix.Append(key);
      m_Suffix.Append("=");
      m_Suffix.Append(value);
    }
    
    public string ToString(string baseUrl) {
      if (baseUrl == null)
        throw new ArgumentNullException("baseUrl");
      return baseUrl + m_Suffix.ToString();
    }

    public static HandlerUrl GetCachedReportURL(Guid reportID) {
      HandlerUrl result = new HandlerUrl(typeof(PageHandler));
      result.AddParameter("id", reportID.ToString("N"));
      return result;
    }

    public static HandlerUrl GetResourceUrl(string resourceName) {
      HandlerUrl result = new HandlerUrl(typeof(FileHandler));
      result.AddParameter("file", resourceName);
      return result;
    }
  }
}
